package com.deer.im.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration;

/**
 * Websocket配置类
 * @author deer
 * @date 2021年11月28日
 */
@Configuration
@EnableWebSocketMessageBroker
@Component
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
	
	//心跳检测常量
	private static long HEART_BEAT = 10000;

	/**
	 * 注册 Stomp的端点 addEndpoint：添加STOMP协议的端点
	 * @author deer
	 * @date 2021年11月30日
	 * @param registry
	 */
	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		//允许使用socketJs方式访问，访问点为webSocket，允许跨域
		registry.addEndpoint("/message").setAllowedOrigins("*");
		registry.addEndpoint("/message").setAllowedOrigins("*").withSockJS();
	}

	@Override
	public void configureWebSocketTransport(WebSocketTransportRegistration registry) {
		// 设置最大消息发送长度
		registry.setMessageSizeLimit(500 * 1024 * 1024);
		registry.setSendBufferSizeLimit(1024 * 1024 * 1024);
		registry.setSendTimeLimit(20 * 10000);
	}

	/**
	 * 配置消息代理 启动Broker，消息的发送的地址符合配置的前缀来的消息才发送到这个broker
	 * @author deer
	 * @date 2021年11月30日
	 * @param registry
	 */
	@Override
	public void configureMessageBroker(MessageBrokerRegistry registry) {
//		registry.enableSimpleBroker("/topic");// 推送消息前缀
//		registry.setApplicationDestinationPrefixes("/topic");
//		registry.setUserDestinationPrefix("/user");// 推送用户前缀
		
		ThreadPoolTaskScheduler te = new ThreadPoolTaskScheduler();
        te.setPoolSize(1);
        te.setThreadNamePrefix("wss-heartbeat-thread-");
        te.initialize();
        registry.enableSimpleBroker("/topic", "/user").setHeartbeatValue(new long[]{HEART_BEAT, HEART_BEAT}).setTaskScheduler(te);
        registry.setUserDestinationPrefix("/user");// 推送用户前缀
        registry.setApplicationDestinationPrefixes("/topic");// 应用请求前缀
	}

}
